import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

import 'TokenUtil.dart';
import 'eventbus.dart';

class NetworkService {
  final _dio = Dio();

  NetworkService() {
    // 配置基础地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    // 设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    // 设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    // 设置请求头
    _dio.options.headers = {'Content-Type': 'application/json'};
    // 添加请求和响应拦截器
    _addInterceptors();
  }

  _addInterceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        // 在请求之前添加token
        // 请求拦截器：添加公共请求参数、token 等
        final token = TokenManager().getToken() ?? '';
        if (token.isNotEmpty) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        return handler.next(options);
      },
      onResponse: (response, handler) async {
        // 在响应之后做些什么
        return handler.next(response);
      },
      onError: (e, handler) async {
        // 在请求失败时做些什么
        return handler.next(e);
      },
    ));
  }

  // 网络请求
  /**
   * 发起GET请求
   * [url] 请求的URL
   * [params] 请求的查询参数
   * 返回解析后的响应数据或错误信息
   */
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      final response = await _dio.get(url, queryParameters: params);
      debugPrint('请求URL：$url' + ',response = ' + response.toString());
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> post(String path, dynamic data) async {
    try {
      var res = await _dio.post(path, data: data);
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> put(String path, dynamic data) async {
    try {
      var res = await _dio.put(path, data: data);
      debugPrint('请求URL：$path' + ',response = ' + res.toString());
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  Future<dynamic> delete(String path, dynamic? data) async {
    try {
      var res = await _dio.delete(path, data: data);
      return handleResponse(res);
    } catch (e) {
      return handleError(e);
    }
  }

  // 处理响应
  dynamic handleResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败，状态码：${response.statusCode}');
    }
  }

  // 处理错误
  dynamic handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        if (error.response?.statusCode == 401) {
          TokenManager().removeToken();
          // 通过事件通知登录页面退出登录
          eventBus.fire(LogoutEvent(''));
        } else {
          throw Exception('响应错误，状态码：${error.response?.statusCode}');
        }
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

class Http {
  static final NetworkService _instance = NetworkService();

  static NetworkService getInstance() {
    return _instance;
  }
}
